<template>
  <PageWrapper title="服务器详情页" contentBackground>
    <Card
      :tab-list="tabListTitle"
      v-bind="$attrs"
      :active-tab-key="activeKey"
      @tabChange="onTabChange"
    >
      <p v-if="activeKey === 'tab1'">
        <VisitAnalysis />
      </p>
      <p v-if="activeKey === 'tab2'">
        <VisitAnalysisBar />
      </p>
    </Card>
    <a-divider type="vertical" />
    <Description @register="registerDesc" />
    <template #footer>
      <a-button class="ml-1;mt-2" @click="openEditObjectModel" type="primary" size="large">
        编辑机器配置
      </a-button>
      <a-divider type="vertical" />
      <a-button class="ml-1;mt-2" @click="openGetTokenModel" type="primary" size="large">
        获取机器密钥
      </a-button>
      <a-divider />
    </template>
    <a-divider />
    <BasicTable
      :bordered="true"
      :canResize="false"
      :striped="true"
      :pagination="{ pageSize: 5 }"
      showTableSetting
      @register="registerRuleTable"
    >
      <template #toolbar>
        <a-button type="primary" @click="openAddRuleModel"> 新增规则配置</a-button>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'clarity:note-edit-line',
              tooltip: '编辑规则',
              onClick: openEditRuleModel.bind(null, record),
            },
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              tooltip: '删除规则',
              popConfirm: {
                title: '是否确认删除',
                confirm: deleteRuleItem.bind(null, record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <a-divider />
    <BasicTable
      :bordered="true"
      :canResize="false"
      :striped="true"
      @register="registerSettingTable"
      showTableSetting
    >
      <template #toolbar>
        <a-button type="primary" @click="openAddSettingModel"> 新增聚合配置</a-button>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'clarity:note-edit-line',
              tooltip: '编辑设置',
              onClick: openEditSettingModel.bind(null, record),
            },
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              tooltip: '删除设置',
              popConfirm: {
                title: '是否确认删除',
                confirm: deleteSettingItem.bind(null, record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <BasicTable
      :bordered="true"
      :canResize="false"
      :striped="true"
      @register="registerOwnerTable"
      showTableSetting
    />
    <a-divider />
    <EditSettingDialog
      @register="registerEditSetting"
      :minHeight="100"
      @exitEditSetting="exitEditSetting"
    />
    <EditRuleDialog @register="registerEditRule" :minHeight="100" @exitEditRule="exitEditRule" />
    <AddRuleDialog @register="registerAddRule" :minHeight="100" @exitAddRule="exitAddRule" />
    <AddSettingDialog
      @register="registerAddSetting"
      :minHeight="100"
      @exitAddSetting="exitAddSetting"
    />
    <EditObjectDialog
      @register="registerEditObject"
      :minHeight="100"
      @exitEditObject="exitEditObject"
    />
    <GetToken @register="registerOpenGetToken" :minHeight="100" />
  </PageWrapper>
</template>
<script lang="ts">
  import { defineComponent, onBeforeMount, ref } from 'vue';
  import { Description, useDescription } from '/@/components/Description';
  import { BasicTable, TableAction, useTable } from '/@/components/Table';
  import { PageWrapper } from '/@/components/Page';
  import { Divider, Card } from 'ant-design-vue';

  import {
    objectSchema,
    ownerTableSchema,
    ruleToObjectSchema,
    settingToObjectSchema,
  } from '/@/views/object/detail/data';
  import { useRouter } from 'vue-router';
  import { getObject } from '/@/api/monitor/object';
  import { listUsers } from '/@/api/monitor/user';
  import { deleteRule, getRule, listRules } from '/@/api/monitor/rule';
  import { deleteSetting, getSetting, listSettings } from '/@/api/monitor/setting';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { StdResponse } from '/@/api/model/baseModel';
  import { useModal } from '/@/components/Modal';
  import EditSettingDialog from '/@/views/setting/edit/EditSettingDialog.vue';
  import EditRuleDialog from '/@/views/rule/edit/EditRuleDialog.vue';
  import { Object, Rule, Setting } from '/@/api/monitor/entity/entity';
  import AddRuleDialog from '/@/views/rule/add/AddRuleDialog.vue';
  import AddSettingDialog from '/@/views/setting/add/AddSettingDialog.vue';
  import EditObjectDialog from '/@/views/object/edit/EditObjectDialog.vue';
  import { useGo } from '/@/hooks/web/usePage';
  import GetToken from '/@/views/object/get/token/GetToken.vue';
  import VisitAnalysis from '/@/views/object/detail/visit/VisitAnalysis.vue';
  import VisitAnalysisBar from '/@/views/object/detail/visit/VisitAnalysisBar.vue';

  export default defineComponent({
    components: {
      GetToken,
      EditObjectDialog,
      AddSettingDialog,
      AddRuleDialog,
      Description,
      BasicTable,
      PageWrapper,
      [Divider.name]: Divider,
      TableAction,
      EditSettingDialog,
      EditRuleDialog,
      VisitAnalysis,
      VisitAnalysisBar,
      Card,
    },
    setup() {
      const go = useGo();
      const { currentRoute } = useRouter();
      const { createMessage } = useMessage();
      const object = ref<Object | null>(null);
      const loadObject = async () => {
        object.value = await getObject(Number(currentRoute.value.params.id));
      };
      onBeforeMount(() => {
        loadObject();
      });

      const listUsersForObjectOwner = async () => {
        return await listUsers({ object_id: Number(currentRoute.value.params.id) });
      };

      const listRulesForObject = async () => {
        return await listRules({ object_id: Number(currentRoute.value.params.id) });
      };

      const listSettingsForObject = async () => {
        return await listSettings({ object_id: Number(currentRoute.value.params.id) });
      };

      const [registerDesc] = useDescription({
        schema: objectSchema,
        column: 1,
        bordered: true,
        size: 'default',
        data: object,
      });
      const [registerRuleTable, { reload: reloadRule }] = useTable({
        title: '受控规则',
        api: listRulesForObject,
        columns: ruleToObjectSchema,
        rowKey: 'id',
        pagination: { pageSize: 5 },
        showIndexColumn: false,
        scroll: { y: 300 },
        actionColumn: {
          width: 120,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
        },
      });
      const [registerSettingTable, { reload: reloadSetting }] = useTable({
        title: '聚合设置',
        api: listSettingsForObject,
        columns: settingToObjectSchema,
        rowKey: 'id',
        pagination: { pageSize: 5 },
        showIndexColumn: false,
        scroll: { y: 300 },
        actionColumn: {
          width: 120,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
        },
      });
      const [registerOwnerTable] = useTable({
        title: '持有用户',
        api: listUsersForObjectOwner,
        columns: ownerTableSchema,
        rowKey: 'id',
        showIndexColumn: false,
        pagination: { pageSize: 5 },
        scroll: { y: 300 },
      });

      const deleteRuleItem = async (record: Recordable) => {
        const resp: StdResponse = await deleteRule(record.id);
        if (resp == null) {
          createMessage.success(`删除规则 ${record.id} 成功`);
        } else {
          createMessage.error(`删除规则 ${record.id} 失败, 错误信息: ` + resp.msg);
        }
        await reloadRule({ page: 1 });
      };

      const deleteSettingItem = async (record: Recordable) => {
        const resp: StdResponse = await deleteSetting(record.id);
        if (resp == null) {
          createMessage.success(`删除聚合设置 ${record.id} 成功`);
        } else {
          createMessage.error(`删除聚合设置 ${record.id} 失败`);
        }
        await reloadSetting({ page: 1 });
      };

      const [registerEditSetting, { openModal: openEditSettingModal }] = useModal();

      async function openEditSettingModel(record: Recordable) {
        const st: Setting = await getSetting(record.id);
        openEditSettingModal(true, { st });
      }

      function exitEditSetting(val: StdResponse) {
        reloadSetting({ page: 1 });
        if (val == null) {
          createMessage.success(`修改聚合配置成功`);
        } else {
          createMessage.error(`修改聚合配置失败, 原因: ` + val.msg);
        }
      }

      const [registerEditRule, { openModal: openEditRuleModal }] = useModal();

      async function openEditRuleModel(record: Recordable) {
        const rl: Rule = await getRule(record.id);
        openEditRuleModal(true, { rl });
      }

      function exitEditRule(val: StdResponse) {
        reloadRule({ page: 1 });
        if (val == null) {
          createMessage.success(`修改规则配置成功`);
        } else {
          createMessage.error(`修改规则配置失败, 原因: ` + val.msg);
        }
      }

      const [registerAddRule, { openModal: openAddRuleModal }] = useModal();

      async function openAddRuleModel() {
        openAddRuleModal(true, { currentRoute });
      }

      function exitAddRule(val: StdResponse) {
        reloadRule({ page: 1 });
        if (val.code == undefined) {
          createMessage.success(`添加规则配置成功, 新规则ID为 ${val}`);
        } else {
          createMessage.error(`添加规则配置失败, 原因: ` + val.msg);
        }
      }

      const [registerAddSetting, { openModal: openAddSettingModal }] = useModal();

      async function openAddSettingModel() {
        openAddSettingModal(true, { currentRoute });
      }

      function exitAddSetting(val: StdResponse) {
        reloadSetting({ page: 1 });
        if (val.code == undefined) {
          createMessage.success(`添加聚合配置成功, 新配置ID为 ${val}`);
        } else {
          createMessage.error(`添加聚合配置失败, 原因: ` + val.msg);
        }
      }

      const [registerEditObject, { openModal: openEditObjectModal }] = useModal();

      async function openEditObjectModel() {
        const obj = object.value;
        openEditObjectModal(true, { obj });
      }

      function exitEditObject(val: StdResponse) {
        if (val) {
          createMessage.error(`修改机器配置失败, 错误信息: ${val.msg}`);
        } else {
          createMessage.success(`修改机器配置成功`);
          go(`/object/list`, true);
        }
      }

      const [registerOpenGetToken, { openModal: openGetTokenModal }] = useModal();

      async function openGetTokenModel() {
        const obj: Object = object.value;
        openGetTokenModal(true, { obj });
      }

      const activeKey = ref('tab1');

      const tabListTitle = [
        {
          key: 'tab1',
          tab: '告警记录',
        },
        {
          key: 'tab2',
          tab: '告警类别',
        },
      ];

      function onTabChange(key) {
        activeKey.value = key;
      }

      return {
        openEditSettingModal,
        openEditRuleModal,
        registerEditSetting,
        registerAddSetting,
        registerEditRule,
        registerOpenGetToken,
        registerEditObject,
        registerAddRule,
        registerOwnerTable,
        registerRuleTable,
        registerDesc,
        objectSchema,
        registerSettingTable,
        deleteRuleItem,
        deleteSettingItem,
        openEditSettingModel,
        exitEditSetting,
        exitEditRule,
        exitEditObject,
        exitAddRule,
        exitAddSetting,
        openEditRuleModel,
        openAddRuleModel,
        openAddSettingModel,
        openEditObjectModel,
        openGetTokenModel,

        activeKey,
        tabListTitle,
        onTabChange,
      };
    },
  });
</script>
<style lang="less" scoped>
  .desc-wrap {
    padding: 16px;
    background-color: @component-background;
  }
</style>
